package com.cjxt.ams.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjxt.ams.dao.UserDao;
import com.cjxt.ams.domain.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author XueYunFei
 * @version V1.0
 * @Description:
 * @className: UserRealm
 * @date 2021/11/24 14:52
 * @company:华勤技术股份有限公司
 * @copyright: Copyright (c) 2021
 */

//继承AuthorizingRealm，够继承到认证与授权功能

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;


    /**
     * @param principalCollection
     * @description: 授权
     * @author XueYunFei
     * @date 2021/11/24 15:01
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * @param authenticationToken
     * @description: 认证
     * @author XueYunFei
     * @date 2021/11/24 15:00
     */

    //Realm将数据库中的数据存放到realm中，由doGetAuthenticationInfo进行数据库操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userAccount = (String) authenticationToken.getPrincipal();
        //查用户信息
        User user = userDao.selectOne(new QueryWrapper<User>().eq("useraccount",userAccount));

//        errorCount++;

        if (user == null) {
            throw new UnknownAccountException("账户不存在，请联系管理员注册");
        }

        if (user.getStatus().equals("N")) {
            throw new LockedAccountException("账户被锁定，请联系管理员");
        }


        /**
         * 返回一个从数据库中查出来的的凭证。用户名为，密码为 。封装成当前返回值
         * 接下来shiro框架做的事情就很简单了。
         * 它会拿你的输入的token与当前返回的这个数据库凭证SimpleAuthenticationInfo对比一下
         * 看看是不是一样，如果用户的帐号密码与数据库中查出来的数据一样，那么本次登录成功
         * 否则就是你密码输入错误
         */


        //SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());

        SimpleAuthenticationInfo authorizationInfo = new SimpleAuthenticationInfo(userAccount, user.getPassword(),getName());
        return authorizationInfo;

    }


}


